﻿// Necroz project team © <2015> <ArchLord2EMU>
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
// 
// Author:Sagara
// Date:2015-09-24-15:11

using System;
using System.Collections.Generic;
using AL2Game.Configs;
using AL2Game.Interfaces;
using AL2Game.Network;
using AL2Game.Network.Frames.Send;
using ArchLord2Commons.Models;
using CM.Framework.UID;

namespace AL2Game.Services
{
    public class LobbyService : ILobbyService
    {
        private static UInt32UidFactory _characterUidFactory = new UInt32UidFactory(); //TODO: Load last character id

        public void Initilize()
        {
           
        }

        public void Release()
        {
            _characterUidFactory = null;
        }

        public void FractionSelected(Al2Connection connection, byte fractionId)
        {
            var accountInfo = connection.AccountInfo;

            if (accountInfo != null)
            {
                //TODO:check for players count
                new SfSelectFraction(fractionId, 2).Send(connection);
            }
        }

        public void CreateCharacter(Al2Connection connection, byte fraction, byte gender, byte classId, byte race,
            string name, byte[] characterData)
        {
            var accountInfo = connection.AccountInfo;

            if(accountInfo == null)
                throw new Exception("Cannot create new character, account info not found");

            int characterFreeId = (int) _characterUidFactory.Next();

            var playerData = new PlayerData(accountInfo.Id, characterFreeId, fraction, classId, race, gender, characterData, name);

            if (connection.CharactersOnAccount == null)
                connection.CharactersOnAccount = new List<PlayerData>();

            if(connection.CharactersOnAccount.Count >= GameServerCfg.Default.MaxPlayersOnAccount)
                return;

            connection.CharactersOnAccount.Add(playerData);

            new SfCreateCharacter(fraction, gender, classId, race, name, characterData).Send(connection, 1);
        }
    }
}